10

Are there any tools available to track the creation and lifetime of Java threads? I would be interested in all of the following:

  • The call stack which called new Thread()
  • The call stack which called start()
  • The lifetime of the run() method
1
  • 1
    Is subclassing an option in your particular environment? Commented Mar 26, 2012 at 15:12

3 Answers 3

5

I have written and published an open source tool to answer this question.

Java Live Thread Analyser

I have blogged about the tool here.

Sign up to request clarification or add additional context in comments.

Comments

4

I don't know of any framework like this. You certainly could subclass the Thread class and store this information on your own like the following. This however will not track Threads that are allocated in other classes such as Executors, etc..

 public class MyThread extends Thread { StackTraceElement[] constructorTrace; StackTraceElement[] startTrace; long runStartTimeMillis; long runFinishTimeMillis; // you'll need to duplicate the constructors you need public MyThread() { super(); constructorTrace = Thread.currentThread().getStacktrace(); } @Override public void start() { super.start(); startTrace = Thread.currentThread().getStacktrace(); } @Override public void run() { runStartTimeMillis = System.currentTimeMillis(); super.run(); runFinishTimeMillis = System.currentTimeMillis(); } } 

4 Comments

You can also use Thread.currentThread().getStacktrace() and System.nanoTime() for timing. You can also just store the new Throwable and only take the StackTrace if you need it.
Thanks @Peter re: Thread.getStacktrace(). I forgot about that. The stacktrace is filled in the Throwable constructor so I don't think that saves anything.
The stack trace element array is not actually filled until it is called for the first time.
Oh. I see. getStackTraceElement I guess translates the native structures into Java StackTraceElement. Makes sense. Thanks.
0

VisualVM now(*) has a tab for threads

enter image description here

(*) Not sure since when

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.